package com.lanxiao.cloud.modules.dict.application;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanxiao.cloud.common.core.enums.DelFlagEnum;
import com.lanxiao.cloud.common.core.utils.StringUtils;
import com.lanxiao.cloud.common.redis.template.RedisTemplateUtils;
import com.lanxiao.cloud.common.web.service.ILog;
import com.lanxiao.cloud.modules.dict.application.assembler.DictAssembler;
import com.lanxiao.cloud.modules.dict.application.dto.DictBaseDto;
import com.lanxiao.cloud.modules.dict.application.dto.DictDto;
import com.lanxiao.cloud.modules.dict.domain.model.Dict;
import com.lanxiao.cloud.modules.dict.infrastructure.constant.DictRedisConstant;
import com.lanxiao.cloud.modules.dict.infrastructure.repository.DictMapper;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-09-26
 */
@Component
public class DictQueryManager implements ILog<Dict, Long> {

  private final DictMapper dictMapper;
  private final DictAssembler dictAssembler;

  public DictQueryManager(
      DictMapper dictMapper,
      DictAssembler dictAssembler) {
    this.dictMapper = dictMapper;
    this.dictAssembler = dictAssembler;
  }

  public Map<String, List<DictBaseDto>> queryAll() {
    Map<String, List<DictBaseDto>> map = RedisTemplateUtils.hashGet(DictRedisConstant.DICT_DATA);
    if (map.size() > 0) {
      return map;
    }
    map = dictAssembler.toDictBaseDto(
        dictMapper.selectList(new LambdaQueryWrapper<Dict>()
            .eq(Dict::getDelFlag, DelFlagEnum.NOT_DELETE)
            .orderByAsc(Dict::getSort)));
    RedisTemplateUtils.hashsSet(DictRedisConstant.DICT_DATA, map);
    return map;
  }


  public List<DictDto> queryType(String type) {
    return dictAssembler.toDictDto(dictMapper.selectList(
        new LambdaQueryWrapper<Dict>()
            .eq(StringUtils.isNotBlank(type), Dict::getType, type)
            .eq(Dict::getDelFlag, DelFlagEnum.NOT_DELETE)
            .orderByAsc(Dict::getSort)));
  }

  @Override
  public Dict selectById(Long id) {
    return dictMapper.selectById(id);
  }

}
